import { useState, useEffect } from 'react';
import { View, Image } from '@tarojs/components';

import './index.scss';

interface CascadeCardProps {
 cardList: Item[];
 onTap?: (item: Item) => void;
}

interface Item {
 id: number;
 url: string;
 title: string;
 subtitle: string;
}
// Related

const CascadeCard: React.FC<CascadeCardProps> = ({ cardList = [], onTap = () => { } }) => {
 const [columns, setColumns] = useState<Item[][]>([[], []]);

 useEffect(() => {
  const newColumns = distributeItems(cardList);
  setColumns(newColumns);
 }, [cardList]);

 const distributeItems = (items: Item[]): Item[][] => {
  const cols: Item[][] = [[], []];
  const colHeights = [0, 0];


  items.forEach((item) => {
   console.log('colHeights', colHeights);
   const colIndex = colHeights[0] <= colHeights[1] ? 0 : 1;
   cols[colIndex].push(item);
   // 模拟高度，实际场景中你需要计算每个元素的高度
   colHeights[colIndex] += 1;
  });

  return cols;
 };

 return (
  <View className='cascade-card-container'>
   {columns.map((col, colIndex) => (
    <View key={colIndex} className='cascade-card-column'>
     {col.map((item, index) => (
      <View
       key={item.id}
       className='cascade-card-item'
       onClick={() => onTap && onTap(item)}
      >
       <Image
        className='cascade-card-item-img'
        style={{ width: '330rpx', height: '330rpx' }}
        mode="aspectFill"
        lazyLoad={true}
        src={item?.url}
       />
       <View className='cascade-card-item-title'>{item?.title}</View>
       <View className='cascade-card-item-subtitle'>{item?.subtitle}</View>
      </View>
     ))}
    </View>
   ))}
  </View>
 );
};

export default CascadeCard;
